<?php

namespace App\Services;

use App\Enum\OrderEnum;
use App\Enum\TravelEnum;
use App\Enum\VillagerEnum;
use App\Models\ActivityApplicationModel;
use App\Models\ActivityModel;
use App\Models\OrderModel;
use App\Models\VillagerUserModel;
use App\Services\Tools\HelpService;
use Illuminate\Support\Facades\DB;

class ActivityApplicationService
{
    /**
     * 活动报名列表
     * @return array
     */
    public static function getActivityApplicationList($id)
    {
        //查询报名记录
        $page = ActivityApplicationModel::query()
            ->select('user_id')
            ->where('activity_id', $id)
            ->orderBy("created_at", "desc")
            ->paginate(HelpService::perPage());
        $ids = null;
        foreach ($page->items() as $k => $v) {
            $ids[] = $v['user_id'];
        }
        if (empty($ids)) {
            return null;
        }
        //查询用户信息
        $userData = ActivityApplicationModel::query()
            ->leftJoin('user as u', 'activity_application.user_id', '=', 'u.id')
            ->where('activity_id', $id)
            ->whereIn('u.id', $ids)
            ->where('activity_application.state', 1)
            ->get()->toArray();

        $orderInfo = OrderModel::query()
            ->whereIn('user_id', $ids)
            ->get()->toArray();

        $orderInfo = array_column($orderInfo, null, 'user_id');

        if (!empty($userData)) {
            foreach ($userData as $k => $v) {
                if (isset($orderInfo[$v['user_id']])) {
                    $userData[$k]['volunteer_status'] = $orderInfo[$v['user_id']]['volunteer_status'] == 1 ? '已上车' : '待出行';
                }
            }
        }
        return HelpService::resultsPageSetData($page, $userData);
    }

    /**
     * 报名
     * @throws \Exception
     */
    public static function activityApplication($id, $userId, $appId)
    {
        $arr = [
            'activity_id' => $id,
            'user_id' => $userId,
            'user_type'=> $appId
        ];
        $userData = ActivityApplicationModel::query()->where($arr)->first();
        if (!empty($userData) && $userData['state'] == 1) {
            throw new \Exception('请勿重复报名');
        }
        $activity = ActivityModel::query()
            ->select()
            ->where('end_time', ">=", date('Y.m.d'))
            ->where(['id' => $id])
            ->first();
        if (empty($activity)) {
            throw new \Exception('活动已结束');
        }
        if ($activity->state == 0) {
            throw new \Exception('活动在审核中，请耐心等待');
        }
        // 补充填写必要字段
        $arr['community_id'] = $activity->community_id;
        $arr['amount'] = $activity->amount;
        $arr['application_no'] = HelpService::createRandNum();

        if (!empty($userData) && $userData['state'] == 0) {
            $res = ActivityApplicationModel::query()->where(['id' => $userData['id']])->update(['state' => 1]);
            if (!$res) {
                throw new \Exception('报名失败');
            }
        }else{
            $activityList = ActivityApplicationModel::query()->create($arr);
            if (!$activityList) {
                throw new \Exception('报名失败');
            }
        }
        // 活动报名人数+1 20231025 by LC
        if( $appId == TravelEnum::PLATFORM_VOLUNTEER ) $incField= 'apply_volunteer_num';
        else $incField = 'apply_num';
        ActivityModel::query()->where(['id'=>$id])->increment($incField);

        return true;
    }

    /**
     * 取消报名
     * @throws \Exception
     */
    public static function activityApplicationCancel($id, $userId, $appId)
    {
        $where = [
            'activity_id' => $id,
            'user_id' => $userId,
            'platform_id'   => $appId
        ];
        $userData = ActivityApplicationModel::query()->where($where)->first();
        if (!empty($userData) && $userData['state'] == 0) {
            throw new \Exception('请勿重复操作');
        }
        // 活动报名人数-1 20231025 by LC
        if( $appId == TravelEnum::PLATFORM_VOLUNTEER ) $incField= 'apply_volunteer_num';
        else $incField = 'apply_num';
        ActivityModel::query()->where(['id'=>$id])->decrement('num');
        return ActivityApplicationModel::query()->where(['id' => $userData['id']])->update(['state' => 0]);
    }

}
